package com.tbsoft.ehr.action.sysdata;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionContext;
import com.tbsoft.ehr.action.BaseAction;
import com.tbsoft.ehr.model.Department;
import com.tbsoft.ehr.service.department.DepartmentService;

public class DepartmentAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(DepartmentAction.class);

	private List<Department> deptLst;
	private Department dept;
	
	private DepartmentService departmentService;	

	public List<Department> getDeptLst() {
		return deptLst;
	}

	public void setDeptLst(List<Department> deptLst) {
		this.deptLst = deptLst;
	}

	public Department getDept() {
		return dept;
	}

	public void setDept(Department dept) {
		this.dept = dept;
	}

	public DepartmentService getDepartmentService() {
		return departmentService;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	public String browse() {
		this.deptLst = this.departmentService.getAllDepts();
		return "browse";
	}
	
	public String save(){
		try{	
			if(this.dept.getId().length()==0) {
				this.dept.setId(null);
				Department d= this.departmentService.getDeptByName(this.dept.getName());
				if(d!=null) {
					return errorReturn("该部门已存在");
				}
			} 
			
			this.departmentService.addDepartment(this.dept);
			Map<String,Object> appMap = ActionContext.getContext().getApplication();			
			appMap.put("DEPT_LIST", this.departmentService.getAllDepts());
			setRel("department_browse");
			return SUCCESS;
		} catch(Exception ex){
			log.error("添加/更新部门失败",ex);
			return errorReturn("添加/更新部门失败:"+ex.getMessage());
		}	
	}
	
	public String delete(){
		if(this.dept!=null&&!this.dept.getId().isEmpty()){
			try{
				this.departmentService.deleteDepartment(this.dept);
				Map<String,Object> appMap = ActionContext.getContext().getApplication();			
				appMap.put("DEPT_LIST", this.departmentService.getAllDepts());
				setRel("department_browse");
			} catch(Exception ex) {
				log.error("执行逻辑删除时出错",ex);
				return errorReturn("逻辑删除失败:"+ex.getMessage());
			}
		} else {
			log.info("没有需要删除的对象");
		}
		return SUCCESS;
	}
	
	public String edit(){
		if(this.dept!=null&&this.dept.getId()!=null){
			this.dept = this.departmentService.getDeptById(this.dept.getId());
			return "update";
		}else{
			log.info("没有选中需要编辑的数据");
			return "browse";
		}
	}
}
